import axios from "axios";
import queryString from './querystring';
import {isObject} from "lodash";

const prefix = 'http://172.19.34.9:5000/graphql';
const loginPrefix = 'http://172.19.34.9:5000';
//封装好的get和post接口，调用方法情况action文件
export let instance = axios.create({
    // baseURL: API_URL, //设置默认api路径
    validateStatus: function(status) {
        return status >= 200 && (status < 300 || status === 400); // default
    },
});

export let instanceLogin = axios.create({
    timeout: 2000
});

export const fetchLogin = (url, param) => {
    return instanceLogin.post(`${loginPrefix + url}`, param);
};

export const getData = (url, param) => {
    return axios
        .create({
            // baseURL: API_URL, //设置默认api路径
            validateStatus: function(status) {
                return status >= 200 && (status < 300 || status === 400); // default
            },
            timeout: 3 * 60 * 1000,
        })
        .get(`${prefix + url}`, {
            params: param
        })
};

export const postData = (url, param, time) => {
    return axios
        .create({
            // baseURL: API_URL, //设置默认api路径
            validateStatus: function(status) {
                return status >= 200 && (status < 300 || status === 400); // default
            },
            timeout: time || 3 * 60 * 1000,
        })
        .post(`${prefix + url}`, param).then(res=>{
          return res.data
        });
};

export const postDataV2 = (url, param) => {
  return axios
      .create({
          // baseURL: API_URL, //设置默认api路径
          validateStatus: function(status) {
              return status >= 200 && (status < 300 || status == 400); // default
          },
          timeout: 3 * 60 * 1000,
          headers: {
              authorization: "Bearer " + window.localStorage.getItem("fxams-token")
          }
      })
      .post(`${prefix + url}`, param).then(res=>{
        return res.data
      });
};
let location = window.location;
export function getLogin() {
  return new Promise(async (resolve, reject) => {
      const parsed = queryString.parse(location.search);
      const kgLoginTicket = parsed.kgLoginTicket;
      const opd = window.localStorage.getItem("opd");
      // const userName = CookieUtil.get("userName");
      const result = await fetchLogin("/login", {
          callbackUrl: location.host,
          kgLoginTicket: kgLoginTicket,
          opd: opd
      });
      const res = result.data;
      if (res.status == 0) {
          location.href = res.redirectUrl;
      } else {
          const token = res.token;
          const userData = res.userInfo;
          if (userData) {
              window.localStorage.setItem(
                  "opd",
                  isObject(userData) ? JSON.stringify(userData) : userData
              );
          }
          window.localStorage.setItem("fxams-token", token);
          resolve();
      }
  });
}
